$(function() {

	$('#timePicker').datetimepicker({
		pickDate : true,
		pickTime : false,
		format : 'YYYY年MM月DD日',
		language : 'zh-CN',
	});
	$('.selectpicker').selectpicker({
		style : 'btn',
		size : 8,
		showContent : false
	});

	if (window.errorMsg) {
		$("#alert-warning").html(window.errorMsg).removeClass("hidden").hide().fadeIn("slow");
		$("#alert-warning").fadeOut(5000);
	}

	validationOption = {
		rules : {
			projectName : {
				required : true
			},
			name : {
				required : true
			},
			key : {
				required : true
			},
			type : {
				required : true
			},
			format : {
				required : true
			}

		},
		messages : {
			projectName : {
				required : "请选择项目名称！",
			},
			name : {
				required : "请输入设备名称！"
			},
			key : {
				required : "请输入设备标识！"
			},
			type : {
				required : "请输入设备类型！"
			},
			format : {
				required : "请输入数据格式！"
			}
		},
		highlight : function(element) {
			$(element).closest('.form-group').addClass('has-error');
		},
		unhighlight : function(element) {
			$(element).closest('.form-group').removeClass('has-error');
		},
		errorElement : 'span',
		errorClass : 'help-block',
		errorPlacement : function(error, element) {
			if (element.parent('.input-group').length) {
				error.insertAfter(element.parent());
			} else {
				error.insertAfter(element);
			}
		}

	};
	$('#addForm').validate(validationOption);
	$('#editForm').validate(validationOption);
	var table = $('#device')
			.DataTable(
					{
						"processing" : true,
						"serverSide" : true,
						"dom" : 'tr<"bottom"ip>',
						"ajax" : {
							"url" : window.basePath + "device/list",
							"type" : "POST",
						},
						"language" : {
							"zeroRecords" : "无数据！",
							"infoEmpty" : "没有找到该条记录！",
							"infoFiltered" : "(共 _MAX_ 条记录)",
							"processing" : "加载中...",
							"lengthMenu" : "_MENU_ Einträge anzeigen",
							"info" : "显示第_START_ 到第 _END_条记录 （共 _TOTAL_ 条记录）",
							"infoPostFix" : "",
							"paginate" : {
								"first" : "第一页",
								"previous" : "上一页",
								"next" : "下一页",
								"last" : "最后一页"
							}
						},
						"createdRow" : function(row, data, index) {
							if (data.status == 1) {
								$(row).addClass('text-danger');
							}
						},
						"columns" : [
								{
									"data" : "projectName"
								},
								{
									"data" : "name"
								},
								{
									"data" : "key"
								},
								{
									"data" : "type"
								},
								{
									"data" : "format"
								},
								{
									"data" : "createTime"
								},
								{
									"data" : "updateTime"
								},
								{
									"class" : "details-control",
									"orderable" : false,
									"data" : null,
									"searchable" : false,
									"defaultContent" : "<button type='button' class='btn btn-success btn-sm'>编辑</button>&nbsp;<button type='button' class='btn btn-danger btn-sm'>删除</button>"
								} ]

					});
	$.fn.dataTable.ext.errMode = 'throw';
	$("#searchProjectName").on('keyup', function() {
		table.column(0).search(this.value).draw();
	});

	$("#searchName").on('keyup', function() {
		table.column(1).search(this.value).draw();
	});
	$("#searchKey").on('keyup', function() {
		table.column(2).search(this.value).draw();
	});

	$("#searchType").on('change', function() {
		if ($(this).get(0).selectedIndex != 0) {
			table.column(3).search(this.value).draw();
		} else {
			table.column(3).search("").draw();
		}
	});
	$("#searchFormat").on('change', function() {
		if ($(this).get(0).selectedIndex != 0) {
			table.column(4).search(this.value).draw();
		} else {
			table.column(4).search("").draw();
		}
	});
	$("#searchTime").on('keyup', function() {
		table.column(5).search(this.value).draw();
	});
	// $("#timePicker").on('dp.change', function(e) {
	// table.column(6).search(e.date.format('YYYY-MM-DD')).draw();
	// });

	$("#device tbody").on(
			"click",
			"button",
			function() {
				var data = table.row($(this).parents('tr')).data();
				if ($(this).hasClass('btn-success')) {
					$.ajax({
						url : window.basePath + "project/loadProject",
						type : "POST",
						success : function(d) {
							rootNode = $("#treeEdit").dynatree("getRoot");
							rootNode.removeChildren();
							rootNode.addChild(d);
							var tree = $("#treeEdit").dynatree("getTree");
							tree.activateKey(data.projectId);
							var node = tree.getNodeByKey(data.projectId);
							$("#projectIdEdit").val(data.projectId);
							$("#projectNameEdit").val(
									node.getParent().getParent().getParent().data.title
											+ node.getParent().getParent().data.title + node.getParent().data.title
											+ node.data.title);
							$("#nameEdit").val(data.name);
							$("#keyEdit").val(data.key);
							$("#typeEdit").val(data.type);
							$("#typeEdit").selectpicker("refresh");
							$("#formatEdit").val(data.format);
							$("#formatEdit").selectpicker("refresh");
							$("#treeTargetEdit").dynatree("getRoot").removeChildren();
							$.ajax({
								url : window.basePath + "target/loadTarget",
								data : {
									id : data.projectId,
									deviceId : data.id,
								},
								type : "POST",
								success : function(d) {
									$("#treeTargetEdit").dynatree("getRoot").addChild(d);
									var treeTargetEdit = $("#treeTargetEdit").dynatree("getTree");
									if (data.targetIds != null) {
										var selectIds = data.targetIds.split(",");
										for (var i = 0; i < selectIds.length; i++) {
											treeTargetEdit.selectKey(selectIds[i], true);
										}
									}
								}
							});
							$("#targetEdit").val(data.targetNames);
							$("#targetIdEdit").val(data.targetIds);
							$("#idEdit").val(data.id);
							$('#editDeviceModal').modal('show');
						}
					});

				} else if ($(this).hasClass('btn-danger')) {
					$("#idDelete").val(data.id);
					$('#deleteDeviceModal').modal('show');
				}

			});

	$("#addDevice").click(function() {
		$("#createDeviceModal").modal('show');
		$.ajax({
			url : window.basePath + "project/loadProject",
			type : "POST",
			success : function(d) {
				rootNode = $("#tree").dynatree("getRoot");
				rootNode.removeChildren();
				rootNode.addChild(d);
			}
		});
	});
	$("#tree").dynatree(
			{
				// checkbox: true,
				selectMode : 1,
				children : [],
				onClick : function(node) {
					if (!node.data.isFolder) {
						$("#projectName").val(
								node.getParent().getParent().getParent().data.title
										+ node.getParent().getParent().data.title + node.getParent().data.title
										+ node.data.title);
						$("#projectId").val(node.data.key);
						$("#tree").hide();
						$("#target").val("");
						targetRootNode = $("#treeTarget").dynatree("getRoot");
						targetRootNode.removeChildren();
						$.ajax({
							url : window.basePath + "target/loadTarget",
							data : {
								id : node.data.key,
								deviceId : null
							},
							type : "POST",
							success : function(d) {
								targetRootNode.addChild(d);
							}

						});
					}
				}
			});

	$("#projectName").click(function(event) {
		$("#tree").toggle();
		$(document).one("click", function() {// 对document绑定一个影藏Div方法
			$("#tree").hide();
		});
		event.stopPropagation();// 点击Button阻止事件冒泡到document
	});
	$("#tree").click(function(event) {
		event.stopPropagation();// 在Div区域内的点击事件阻止冒泡到document
	});
	$("#treeTarget").dynatree({
		checkbox : true,
		selectMode : 3,
		persist : true,
		onPostInit : function(isReloading, isError) {
			this.reactivate();
		},

		onSelect : function(select, node) {
			// Get a list of all selected nodes, and convert
			// to a key array:
			var selKeys = $.map(node.tree.getSelectedNodes(), function(node) {
				if (!node.data.isFolder) {
					return node.data.key;
				}
			});
			$("#targetId").val(selKeys.join(","));

			var selTitles = $.map(node.tree.getSelectedNodes(), function(node) {
				if (!node.data.isFolder) {
					return node.getParent().getParent().data.title + node.getParent().data.title + node.data.title;
				}
			});
			$("#target").val(selTitles.join(", "));
		},
		children : [],
		onDblClick : function(node, event) {
			node.toggleSelect();
		},
		onKeydown : function(node, event) {
			if (event.which == 32) {
				node.toggleSelect();
				return false;
			}
		}

	});
	$("#target").click(function(event) {
		$("#treeTarget").toggle();
		$(document).one("click", function() {// 对document绑定一个影藏Div方法
			$("#treeTarget").hide();
		});
		event.stopPropagation();// 点击Button阻止事件冒泡到document
	});
	$("#treeTarget").click(function(event) {
		event.stopPropagation();// 在Div区域内的点击事件阻止冒泡到document
	});
	$("#treeEdit").dynatree(
			{
				selectMode : 1,
				activeVisible : true,
				children : [],
				onClick : function(node) {
					if (!node.data.isFolder) {
						// alert("You activated " + node.data.title);
						$("#projectNameEdit").val(
								node.getParent().getParent().getParent().data.title
										+ node.getParent().getParent().data.title + node.getParent().data.title
										+ node.data.title);
						$("#projectIdEdit").val(node.data.key);
						$("#treeEdit").hide();
						$("#targetEdit").val("");
						$("#treeTargetEdit").dynatree("getRoot").removeChildren();
						$.ajax({
							url : window.basePath + "target/loadTarget",
							data : {
								id : node.data.key,
								deviceId : $("#idEdit").val()
							},
							type : "POST",
							success : function(d) {
								$("#treeTargetEdit").dynatree("getRoot").addChild(d);
							}

						});
					}
				}
			});
	$("#projectNameEdit").click(function(event) {
		$("#treeEdit").toggle();
		$(document).one("click", function() {// 对document绑定一个影藏Div方法
			$("#treeEdit").hide();
		});
		event.stopPropagation();// 点击Button阻止事件冒泡到document
	});
	$("#treeEdit").click(function(event) {
		event.stopPropagation();// 在Div区域内的点击事件阻止冒泡到document
	});

	$("#treeTargetEdit").dynatree({
		checkbox : true,
		selectMode : 3,
		// persist : true,
		children : [],
		onSelect : function(select, node) {
			// Get a list of all selected nodes, and convert
			// to a key array:
			var selKeys = $.map(node.tree.getSelectedNodes(), function(node) {
				if (!node.data.isFolder) {
					return node.data.key;
				}
			});
			$("#targetIdEdit").val(selKeys.join(","));

			var selTitles = $.map(node.tree.getSelectedNodes(), function(node) {
				if (!node.data.isFolder) {
					return node.getParent().getParent().data.title + node.getParent().data.title + node.data.title;
				}
			});
			$("#targetEdit").val(selTitles.join(", "));
		},
		onDblClick : function(node, event) {
			node.toggleSelect();
		},
		onKeydown : function(node, event) {
			if (event.which == 32) {
				node.toggleSelect();
				return false;
			}
		}

	});
	$("#targetEdit").click(function(event) {
		$("#treeTargetEdit").toggle();
		$(document).one("click", function() {// 对document绑定一个影藏Div方法
			$("#treeTargetEdit").hide();
		});
		event.stopPropagation();// 点击Button阻止事件冒泡到document
	});
	$("#treeTargetEdit").click(function(event) {
		event.stopPropagation();// 在Div区域内的点击事件阻止冒泡到document
	});
	$('#collapseOne').on('show.bs.collapse', function() {
		$("#arrow").removeClass("glyphicon glyphicon-chevron-down").addClass("glyphicon glyphicon-chevron-up");
	});
	$('#collapseOne').on('hide.bs.collapse', function() {
		$("#arrow").removeClass("glyphicon glyphicon-chevron-up").addClass("glyphicon glyphicon-chevron-down");
	});
});